﻿using Com.Lancetinc.Evs.Windows;
using System;

namespace Com.Lancetinc.Evs.Helpers
{
    public static class LoginHelper
    {
        public static bool Login(out bool windowShown)
        {
            bool canStartup = false;
            windowShown = false;
            try
            {
                canStartup = AuthorizationHelper.CanBootstrap();
                if (!canStartup)
                {
                    new LicenseWindow().ShowDialog();
                    canStartup = AuthorizationHelper.CanBootstrap();
                    windowShown = true;
                }

                if (canStartup)
                {
                    if (!ShouldAutoLogin())
                    {
                        canStartup = new LoginWindow().ShowDialog() == true;
                        windowShown = true;
                    }
                }
            }
            catch (Exception ex)
            {
                canStartup = false;
                MessageHelper.ShowError(ex.Message);
            }
            return canStartup;
        }

        public static bool ShouldAutoLogin()
        {
            return true;
            var pwd = Properties.Settings.Default.AutoLoginPwd;
            if (string.IsNullOrEmpty(pwd))
                return false;

            var rawPwd = DecodeRawPassword(pwd);
            if (string.IsNullOrEmpty(rawPwd))
                return false;

            // 检查密码是否一致
            return UserHelper.CheckPassword(rawPwd);
        }

        public static void SetAutoLogin(bool isAutoLogin, string pwd = null)
        {
            if (pwd != null)
                pwd = EncodeRawPassword(pwd);

            Properties.Settings.Default.AutoLoginPwd = !isAutoLogin ? string.Empty : pwd;
            Properties.Settings.Default.Save();
        }

        private static string EncodeRawPassword(string pwd)
        {
            return CipherUtils.Rc4Encode(pwd, typeof(LoginHelper).FullName);
        }

        private static string DecodeRawPassword(string rawPwd)
        {
            try
            {
                return CipherUtils.Rc4Decode(rawPwd, typeof(LoginHelper).FullName);
            }
            catch
            {
                return null;
            }
        }
    }
}
